/*
 * Created on Feb 15, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.ui;

import java.io.File;

import org.apache.log4j.Logger;
import org.mortbay.http.HttpContext;
import org.mortbay.http.HttpServer;
import org.mortbay.http.SocketListener;
import org.mortbay.jetty.servlet.ServletHandler;

/**
 * @author dfhuynh
 */
public class Flair {
    final static private Logger s_logger = Logger.getLogger(Flair.class);

    final static public String s_namespace = "http://simile.mit.edu/flair/";

    static public void setupServlet(
            HttpContext context, File flairDir, Class servletClass)
            throws Exception {

        context.setInitParameter("flairDir", flairDir.getCanonicalPath());

        ServletHandler servlets = new ServletHandler();
        servlets.addServlet("Flair", "/*", servletClass.getName());
        context.addHandler(servlets);
    }

    static public HttpServer createWebServer(
        File        flairDir,
        String      host,
        String      contextPath,
        Class       servletClass,
        int         port
    ) throws Exception {
        s_logger.info(
            "Setting up HTTP Server \n" +
            "\thost " + (host != null ? host : "0.0.0.0") + "\n" +
            "\tport " + port + "\n" +
            "\tcontext " + contextPath + "\n" +
            "\tfrom " + flairDir.getCanonicalPath()
        );

        HttpServer httpServer = new HttpServer();
        SocketListener listener = new SocketListener();
        if (host != null) listener.setHost(host);
        listener.setPort(port);
        listener.setMinThreads(5);
        listener.setMaxThreads(250);
        httpServer.addListener(listener);

        HttpContext httpContext = new HttpContext();
        httpContext.setContextPath(contextPath);
        httpContext.setClassLoader(Flair.class.getClassLoader());
        Flair.setupServlet(httpContext, flairDir, servletClass);

        httpServer.addContext(httpContext);

        return httpServer;
    }
}
